<?php



namespace app\console\controller;



namespace app\console\controller;



use think\Session;

use think\Url;

use think\Cache;

use think\Loader;

use think\Request;

use think\Controller;

use app\console\model\Ad as AdModel;

use app\console\model\Single as Model;

use app\common\trilateral\Classify as ClassifyAlias;

use think\Db;

use think\Debug;

class Single extends Controller

{





    /**

     * 前置方法

     */

    protected $beforeActionList = [

        'clearCache' => ['only'],

    ];



    /**

     * 服务二级类以及金额  订单修改里

     */

    public function ajax2($id,$shop_id = 0,$order_id,$t_type = 1)

    {

//        $data = Db::name('single')

//            ->where('auding_status', 2)

//            ->where('is_delete', 1)

//            ->where('parent_id', $id)

//            ->select()->toArray();

        if($t_type == 1){

            $table = 'order_gift_count';

        }

        if($t_type == 2){

            $table = 'order_mc_count';

        }

        $data = Db::name($table)

            ->alias('ogc')

            ->join('single s','ogc.single_content = s.id')

            ->where('order_id',$order_id)

            ->where('ogc.single_id',$id)

            ->where('ogc.gift_count','gt',0)

            ->whereTime('ogc.end_time','>=',time())

            ->select()->toArray();

        $gift_id = Db::name('order')->where('id',$order_id)->value('gift_id');

        if(!empty($data)){

            foreach ($data as $k => &$v){

                $person_price = Db::name('shop_service_price')->where('shop_id',$shop_id)->where('single_id',$v['id'])->value('person_price');

                $v['person_price'] = is_null($person_price) ? 0 :$person_price;

                //$v['person_price'] = $v['person_price']+Db::name('gift_shop_price')->where('gift_id',$gift_id)->where('shop_id',$shop_id)->value('price');

            }

        }else{

            $data[0]['cat_name'] = '';

            $data[0]['person_price'] = 0;

        }

        return $data;

    }



    /**

     * @param $id

     * @param int $shop_id

     * @param $order_id

     * @param int $t_type

     * @return array

     * 服务金额

     */

    public function ajax2a($single_id,$shop_id = 0)

    {



        $service_people_price2 = Db::name('single')->field('id,cat_name,parent_id,sort')->where('is_delete',1)->where('auding_status',2)->where('parent_id',$single_id)->order(['sort' => 'asc','id' => 'asc'])->select()->toArray(); //服务人员提成;;

        foreach ($service_people_price2 as &$v){

            $price = Db::name('single_shop_price')->where('shop_id',$shop_id)->where('single_id',$v['id'])->value('price');

            if(is_null($price)) $price = 0.00;

            $v['person_price'] = $price;

        }

        return $service_people_price2;

    }



    public function shop_ticheng($id)

    {

        $goods_id = input('id');

        $shop_list = Db::name('shop')->where('auding_status', 2)->where('is_delete', 1)->select()->toArray();

        if(!empty($shop_list)){

            foreach ($shop_list as &$v){

                $v['price'] = Db::name('single_shop_price')->where('single_id',$goods_id)->where('shop_id',$v['id'])->value('price');

            }

        }

        $title = Db::name('single')->where('id',$id)->value('cat_name');

        return view('', ['shop_list' => $shop_list,'title' => $title]);

    }



    public function single_ajax($shop_id,$single_id){

        $price = Db::name('single_shop_price')->where('single_id',$single_id)->where('shop_id',$shop_id)->value('price');

        if(is_null($price)) $price = 0;

        return $price;

    }

    public function single_ajax_goods_shop_price1($shop_id,$single_id){

        $price = Db::name('goods_shop_price1')->where('goods_id',$single_id)->where('shop_id',$shop_id)->value('price');

        if(is_null($price)) $price = 0;

        return $price;

    }



    public function servicePriceUpdate()

    {

        $goods_id = input('single_id');

        $param = Request::instance()->param()['input2'];



        if (!empty($param)) {

            $ret = false;

            foreach ($param as $k => $v) {

                $find = Db::name('single_shop_price')->where('shop_id', $k)->where('single_id', $goods_id)->find();

                if($find){ //存在就是修改

                    $ret = Db::name('single_shop_price')->where('shop_id', $k)->where('single_id', $goods_id)->update(['price' => $v]);

                }else{

                    $ret = Db::name('single_shop_price')->insert([

                        'single_id' => $goods_id,

                        'shop_id' => $k,

                        'price' => $v,

                    ]);

                }



            }

            if ($ret !== false) {

                win('门店销售金额设置完毕', Url::build('index',['id' => $goods_id]));

            }

        }

    }



    public function ajax22($id, $shop_id, $gift_id)

    {

        $data = Db::name('gift_count gc')

            ->where('gift_id', $gift_id)

            ->where('single_id', $id)

            ->join('single s', 'gc.single_content = s.id')

            ->select()->toArray();

        foreach ($data as $k => &$v) {

            $person_price = Db::name('shop_service_price')->where('shop_id', $shop_id)->where('single_id', $v['single_content'])->value('person_price');

            $v['person_price'] = is_null($person_price) ? 0 : $person_price;

        }

        return $data;

    }



    /**

     * @param $id

     * @param int $shop_id

     * @return mixed 获得自己分类的金额

     */

    public function ajax4($id,$shop_id = 0,$order_id = 0)

    {

        $person_price = Db::name('shop_service_price')->where('shop_id',$shop_id)->where('single_id',$id)->value('person_price');

        $gift_id = Db::name('order')->where('id',$order_id)->value('gift_id');

        Db::name('gift_shop_price')->where('gift_id',$gift_id)->where('shop_id',$shop_id)->value('price');

        return $person_price;

        //return $person_price+Db::name('gift_shop_price')->where('gift_id',$gift_id)->where('shop_id',$shop_id)->value('price');;

    }



    public function ajax4a($id,$shop_id = 0,$order_id = 0)

    {

        $person_price = Db::name('single_shop_price')->where('shop_id',$shop_id)->where('single_id',$id)->value('price');

        return $person_price;

        //return $person_price+Db::name('gift_shop_price')->where('gift_id',$gift_id)->where('shop_id',$shop_id)->value('price');;

    }



    /**

     * @param $id

     * @param int $shop_id

     * @return array

     * 会员卡ajax

     */

    public function ajax2m($id,$shop_id = 0)

    {

        $data = Db::name('single')

            ->where('auding_status', 2)

            ->where('is_delete', 1)

            ->where('parent_id', $id)

            ->select()->toArray();



        if(!empty($data)){

            foreach ($data as $k => &$v){

                $person_price = Db::name('shop_service_price')->where('shop_id',$shop_id)->where('single_id',$v['id'])->value('person_price');

                $v['person_price'] = is_null($person_price) ? 0 :$person_price;

            }

        }else{

            $data[0]['cat_name'] = '';

            $data[0]['person_price'] = 0;

        }

        return $data;

    }





    /**

     * 广告位列表

     */

    public function index()

    {



        Debug::remark('begin');



        $param = Request::instance()->param();



        $where = [];

        if(!empty($param['title'])) $where['cat_name'] = ['like','%'.$param['title'].'%'];



        $current_id = Db::name('single')->where($where)->where(' is_delete = 1')->select();

        $new_array = Db::name('single')->where($where)->where(' is_delete = 1')->column('id');



        if(!empty($current_id)){

            foreach ($current_id as $k => $v){

                if($v['parent_id'] != 0){

                    $new_array[] = Db::name('single')->where('id',$v['parent_id'])->value('id');

                }

            }

        }

        $where2['id'] = ['in',$new_array];

        $data = Model::where($where2)->order(['sort' => 'asc','id' => 'asc'])->select();//默认asc

        foreach ($data as $v){



        }

       // halt($data);

        //$data = $this->array_sort($data,'sort');

        //$data = $this->array_sort($data,'sort','desc');

        $data = getMenuTree($data);

        //$data = $this->array_sort($data,'sort');

        Debug::remark('end');

        if(isset($param['export'])){

            $this->push($data);

        }



        //echo Debug::getRangeTime('begin','end').'s';

        return $this->fetch('', [

            'data' => $data,



        ]);

    }



    public function array_sort($arr, $keys, $type = 'asc')

    {

        $keysvalue = $new_array = array();

        foreach ($arr as $k => $v) {

            $keysvalue[$k] = $v[$keys];

        }

        if ($type == 'asc') {

            asort($keysvalue);

        } else {

            arsort($keysvalue);

        }

        reset($keysvalue);

        foreach ($keysvalue as $k => $v) {

            $new_array[$k] = $arr[$k];

        }

        return $new_array;

    }



    public function push($data,$name = '服务类导出')

    {



        set_time_limit(0);

        ini_set('memory_limit', '1024M');

        error_reporting(E_ALL);

        date_default_timezone_set('Asia/Shanghai');



        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');

        $objPHPExcel = new \PHPExcel();



        /*以下是一些设置 ，什么作者  标题啊之类的*/

        $objPHPExcel->getProperties()->setCreator("管理员")

            ->setLastModifiedBy("管理员")

            ->setTitle("电话本导出")

            ->setSubject("数据EXCEL导出")

            ->setDescription("备份数据")

            ->setKeywords("excel")

            ->setCategory("result file");

        $objPHPExcel->setActiveSheetIndex(0)

            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

            ->setCellValue('A1', '科目代码')

            ->setCellValue('B1', '借贷方(绿色借方-灰色贷方)')

            ->setCellValue('C1', 'ID')

            ->setCellValue('D1', '标题')

            ->setCellValue('E1', '创建时间')

        ;

        $sheet1 = [];



        for ($x = 0; $x < count($sheet1); $x++) {

            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(

                array(

                    'font'      => array(

                        'bold' => true

                    ),

                    'alignment' => array(

                        'horizontal' =>

                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER

                    )

                )

            );

        }



        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/



        $n = 0;

        foreach ($data as $v) {



            $num = $n + 2;

            $objPHPExcel->setActiveSheetIndex(0)

                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推

                ->setCellValue('A' . $num, $v['code'])

                ->setCellValue('B' . $num, $v['dc_text'])

                ->setCellValue('C' . $num, $v['id'])

                ->setCellValue('D' . $num, str_repeat('--',$v['level']).$v['cat_name'])

                ->setCellValue('E' . $num, $v['create_time'])

            ;

            $n++;

        }



        $objPHPExcel->getActiveSheet(0)->setTitle('服务类导出');

        $objPHPExcel->setActiveSheetIndex(0);



        ob_end_clean();

        header('Content-Type: application/vnd.ms-excel');

        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');

        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

        $objWriter->save('php://output');

        exit;

    }



    public function code(){

        $param = Request::instance()->param()['code'];



        if(!empty($param)){



            foreach ($param as $k => $v){



                $ret = Db::name('single')->where('id',$k)->setField('code',$v);

            }

            if($ret !== false){

                win('科目代码设置成功',Url::build('index'));

            }

        }



    }





    /**

     * 广告位创建

     */

    public function create(Request $request, Model $model)

    {



        if ($request->instance()->isPost()) {



            $data = $request->instance()->param();



//            // 验证

//            $validate = Loader::validate('AdType');

//            if (!$validate->scene('create')->check($data)) fail($validate->getError());



            // 提交数据

            if($data['parent_id'] == 0){

                fail('不允许添加一级分类');

            }

            $dispose = $model->allowField(true)->save($data);



            if ($dispose) {

                win('操作成功', Url::build('index'));

            }



            fail('操作失败');



        }



        $news_type = Db::name('single')->where(['auding_status' => 2,'is_delete' => 1,'parent_id' => 0])->select();

        return $this->fetch('create', [

            "news_type" => $news_type,

        ]);



    }





    /**

     * 广告位编辑

     */

    public function update($id, Request $request, Model $model)

    {



        if ($request->instance()->isPost()) {



            $data = $request->instance()->param();

            // 验证

           // $validate = Loader::validate('AdType');

           // if (!$validate->scene('create')->check($data)) fail($validate->getError());



            // 提交数据

            $dispose = $model->allowField(true)->save($data, ['id' => $id]);





            if ($dispose !== false) {

                win('操作成功', Url::build('index'));

            }



            fail('操作失败');



        }



        $item = Model::get($id);

        $news_type = Db::name('single')->where(['auding_status' => 2,'is_delete' => 1,'parent_id' => 0])->select();

        return $this->fetch('create', [

            "news_type" => $news_type,

            'item' => $item

        ]);

    }







    /**

     * 广告位删除

     */

    public function destroy($id, Model $model)

    {



        if (Request::instance()->isGet()) {

            Db::name('single')->where('id',$id)->update(['delete_time' => date('Y-m-d H:i:s',time()),'is_delete' => 2,'delete_id' => session('manage_id')]);

            $title = Db::name('single')->where('id',$id)->find();

            Db::name('recycle_bin')->insert(['title' => $title['cat_name'],'type' =>'单页管理','table' => 'news','table_id' => $id,'delete_id' => Session::get('manage_id'),'delete_time' => date('Y-m-d H:i:s',time())]);

            win('操作成功', Url::build('index'));

        }

        fail('操作失败');



    }

    /**

     * 栏目状态改变

     */

    public function dc($id, Request $request, Model $model)

    {

        $id = $request->instance()->param('id');



        $status = $model->where('id', $id)->value('dc') == '1' ? 2 : 1;



        if ($model->where('id', $id)->update(['dc' => $status])) {

            return $status;

        }

        return false;

    }



    /**

     * 栏目状态改变

     */

    public function status($id, Request $request, Model $model)

    {

        $id = $request->instance()->param('id');



        $status = $model->where('id', $id)->value('status') == '1' ? 2 : 1;



        if ($model->where('id', $id)->update(['status' => $status])) {

            return $status;

        }

        return false;

    }





    /**

     * 栏目全部删除

     */

    public function destroyAll($id, AdTypeModel $adType)

    {



        if ($adType->amputateAll($id)) {



            win('操作成功', Url::build('AdType/index'));

        }



        fail('操作失败');



    }











    /*

    * 排列顺序

    */

    public function sorting()

    {



        $id = Request::instance()->param('orderId/a');

        $sort = Request::instance()->param('sort/a');



        foreach ($id as $key => $value) {

            Db::name('single')->where('id', $value)->update(['sort' => $sort[$key]]);

        }



        win('操作成功', Url::build('index'));

    }



    /**

     * 清除缓存

     */

    protected function clearCache()

    {

        Cache::rm('AdType');

    }

}